var modulosClass = {
	parent: "parentId",
	pattern: "4H",
	win: null,
	form: null,
	grid: null,
	actionBar: null,
	layout: null,
	dhxCombo: null,
	BoleCod: null,
	PregCod: null,
	statusGrid: null,
	widgetWin: function(){
		var windows = new dhtmlXWindows();
		this.win = windows.createWindow('window_1', 0, 0, 500, 400);
		this.win.setText('Modulos');
		this.win.clearIcon();
		this.win.button('park').hide();
		this.win.button('minmax1').hide();
		this.win.denyResize();
		this.win.setModal(1);
		this.win.centerOnScreen();
        widgetBar(this.win,1);
		this.layout = this.win.attachLayout('2E');

	},
    widgetGrid: function(){
        var me = this,
            cell = me.layout.cells('b');
        cell.hideHeader();

        me.statusGrid = cell.attachStatusBar();

        me.grid = cell.attachGrid();
        me.grid.setHeader("Id, Código,Detalle,mod_tipob");
        me.grid.setColTypes("ro,ro,ro,ro");
        me.grid.setColAlign("right,left,left,center");
        me.grid.setInitWidths("30,100,*,83");
        me.grid.setColumnColor("#E5E5E5");
        me.grid.init();

        me.grid.load(mainPath+"index.php/Module/Grid_data", function(){
            me.grid.groupBy(3);
           // me.grid.setColumnHidden(1,true);
            me.grid.setColumnHidden(3,true);
            me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
        },"json");
    },
    widgetForm: function(){
        var me = this,
        cell = me.layout.cells('a');
        cell.hideHeader();
        cell.fixSize(true, true);
        cell.setHeight('110');
        var str = [
            //{type:'hidden',name:'mod_id'},
            { type:"input" , name:"mod_codigo", label:"Codigo:", validate: "NotEmpty", labelWidth:95, labelAlign:"right", inputWidth:200, offsetTop:"10"  },
            { type:"input" , name:"mod_detalle", label:"Detalle:", rows:"2", labelWidth:95, labelAlign:"right", inputWidth:360  },
            { type:"select" , name:"mod_tipob", label:"Tipo de Boleta:", validate: "NotEmpty", labelWidth:95, labelAlign:"right", inputWidth:155,options: [{
                text: "---",
                value:""
            },{
                text: "Boleta de Infraestructura",
                value: "BINF"
            }, {
                text: "Boleta de Gestión",
                value: "BGES"
            }] },
            { type:"button" , name:"save_btn", value:"Guardar", inputLeft:368, inputTop:78, position:"absolute"  },
            { type:"button" , name:"edit_btn", value:"Modificar", inputLeft:260, inputTop:78, position:"absolute"  }
        ];
        me.form = cell.attachForm(str);
        me.form.lock();
       // me.eventClickForm();

        me.form.attachEvent("onButtonClick", function(name) {
            switch(name){
                case 'save_btn':
                    var data = me.form.getFormData();
                    if(me.form.validate()){
                        var auxFind = me.grid.findCell(data.mod_codigo,1);
                        var valCell = (auxFind != '')?me.grid.cells(auxFind[0][0],auxFind[0][1]).getValue():null;
                        if(valCell != data.mod_codigo){
                            me.form.send(mainPath+'index.php/Module/save_data',function(loader, response) {
                               
                                if(response > 0){
                                    var id = me.grid.uid();
                                    me.grid.addRow(response, [response,data.mod_codigo,data.mod_detalle,data.mod_tipob]);
                                    me.grid.selectRowById(id);
                                    me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
                                    me.form.clear();
                                    me.form.lock();
                                    actionBar.enableItem('btn_new');
                                }
                                else
                                    dhtmlx.alert({
                                        text: response
                                    });
                            });
                        }
                        else
                            dhtmlx.alert({
                                text:"Error, ya existe el codigo '"+valCell.toUpperCase()+"', ingrese otro."
                            });
                    }
                    else
                        dhtmlx.alert({
                            text:"Error, Todos los campos de color rojo son necesarios."
                        });
                break;
                case 'edit_btn':
                     var rowId = me.grid.cells(me.grid.getSelectedRowId(),0).getValue();
                    if(me.form.validate()){
                        dhtmlx.confirm({
                            text:"¿Esta seguro de guardar los cambios?",
                             callback: function(status){
                                if(status == true){
                                    me.form.send(mainPath+'index.php/Module/edit_data?id='+rowId, function(loader, response){
                                        if(response == true){
                                            me.grid.cells(rowId,2).setValue(me.form.getFormData().mod_detalle);
                                            me.grid.clearSelection();
                                            me.form.lock();
                                            me.form.clear();
                                            me.form.setItemFocus('btn_new');
                                        }
                                        else
                                            dhtmlx.alert({
                                                text: response
                                            });
                                    });
                                }
                            }
                        });
                    }
                    else
                        dhtmlx.alert({
                            text:"Error"
                        });
                break;
            }
        });


    },
	widgetMain: function(){
		var me=this;
        modulosClass.widgetWin();
        modulosClass.widgetGrid();
        modulosClass.widgetForm();
       // detail.attachObject('detailModule');
        actionBar.attachEvent("onClick", function(itemId){
			switch(itemId){
                case 'btn_new':
                    actionBar.disableItem(itemId);
                    me.form.clear();
                    me.form.unlock();
                    me.form.enableItem('mod_codigo');
                    me.form.setItemFocus('mod_codigo');
                    me.form.disableItem('edit_btn');
                    me.form.enableItem('save_btn');
                break;
				case 'btn_edit':
					var id = me.grid.getSelectedRowId();
					if(id != null){
						me.form.unlock();
						me.form.enableItem('save_btn');
						// me.form.enableItem('edit_btn');
						me.form.setItemValue('mod_codigo', me.grid.cells(id,1).getValue());
						me.form.setItemValue('mod_detalle', me.grid.cells(id,2).getValue());
                        me.form.setItemValue('mod_tipob', me.grid.cells(id,3).getValue());
					} 
					else
						dhtmlx.alert({
							text:"Error seleccione un Ítem para poder editar."
						});
				break;
				case 'btn_erase':
                    if(me.grid.getSelectedRowId() != null){
                        var rowId = me.grid.cells(me.grid.getSelectedRowId(),0).getValue();
                        dhtmlx.confirm({
                            text:"¿Esta seguro que quieres eliminar el Ítem?",
                            callback: function(status){
                                if(status == true){
                                    me.form.send(mainPath+'index.php/Module/erase_data?id='+rowId, function(loader, response){
                                        if(response != true)
                                            dhtmlx.alert({
                                                text: response
                                            });
                                        else{
                                            me.grid.deleteSelectedRows();
                                            me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
                                        }
                                    });
                                }
                            }
                        });
                    }
                    else
                        dhtmlx.alert({
                            text:"Error seleccione un Ítem para poder eliminar."
                        });
				break;
                case 'btn_clear':
					me.form.clear();
				break;
			}
		});
	}
};